<script setup lang="ts">
import {ref} from 'vue'
import {ElMessage} from 'element-plus'
import {SetControllerService, SetVO} from "../../../../generated"

const props = defineProps<{
  visible: boolean
  title?: string
  existingIds?: string[]
}>()

const emit = defineEmits<{
  'update:visible': [value: boolean]
  'select': [set: SetVO]
}>()

const availableSets = ref<SetVO[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取可选的题集列表
const fetchAvailableSets = async () => {
  try {
    const res = await SetControllerService.pageSetUsingPost({
      currentPage: currentPage.value,
      pageSize: pageSize.value
    })
    if (res.data?.records) {
      availableSets.value = res.data.records
      total.value = res.data.total || 0
    }
  } catch (error) {
    ElMessage.error('获取题集列表失败')
  }
}

// 选择题集
const handleSelect = (set: SetVO) => {
  if (props.existingIds?.includes(set.id)) {
    ElMessage.warning('该题集已存在')
    return
  }
  emit('select', set)
  emit('update:visible', false)
}

// 添加页码改变的处理函数
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchAvailableSets()
}

// 添加每页条数改变的处理函数
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchAvailableSets()
}
</script>

<template>
  <el-dialog
      :model-value="visible"
      :title="title || '选择题集'"
      width="70%"
      @update:model-value="$emit('update:visible', $event)"
      @open="fetchAvailableSets"
  >
    <el-table :data="availableSets" style="width: 100%">
      <el-table-column prop="title" label="标题"/>
      <el-table-column prop="target" label="描述"/>
      <el-table-column prop="cover" label="封面预览">
        <template #default="scope">
          <el-image
              v-if="scope.row.cover"
              :src="scope.row.cover"
              style="width: 100px; height: 50px"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button
              type="primary"
              size="small"
              @click="handleSelect(scope.row)"
          >
            选择
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加分页组件 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20,30]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </div>
  </el-dialog>
</template>

<style scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>